<?php

namespace app\admin\controller;

use app\admin\exception\AdminException;
use app\common\entity\AdminRegLog;
use app\common\entity\MachineList;
use app\common\entity\Market;
use app\common\entity\Message;
use app\common\entity\MobileRecharge;
use app\common\entity\Mywallet;
use app\common\entity\MywalletLog;
use app\common\entity\OtcMatch;
use app\common\entity\RealPass;
use app\common\entity\SendMachine;
use app\common\entity\UnsealingList;
use app\common\entity\UserLevelSend;
use app\common\entity\VoucherList;
use app\common\entity\User as userModel;
use app\common\entity\UserInviteCode;
use app\common\entity\UserMagicLog;
use app\common\entity\Export;
use app\common\entity\UserPackage;
use app\common\entity\UserProduct;
use app\common\service\Users\Identity;
use app\common\entity\Product as productModel;
use app\common\shop\RealNameModel;
use app\common\shop\UserAgentLevelModel;
use app\common\shop\UserApplyLogModel;
use app\common\shop\UserAreaLevelModel;
use app\common\shop\UserHouseLevelModel;
use app\common\shop\UserLevelModel;
use app\common\shop\UserTeamLevelModel;
use think\Db;
use think\Exception;
use think\Request;
use app\common\entity\Config;
use app\common\entity\Partnerr;
class User extends Admin
{
    /**
     * [获取审核状态]
     * @param
     * @return
     */
    public function a( Request $request ){
    	// account_pos active_log act_to_fbb admin_reg_log farm_orders my_wallet my_wallet_log orders otc_market otc_match partnerr person_service proportion proportion_copy2  
		Db::query('TRUNCATE `account_pos`');
		Db::query('TRUNCATE `active_log`');
		Db::query('TRUNCATE `act_to_fbb`');
		Db::query('TRUNCATE `admin_reg_log`');
		Db::query('TRUNCATE `farm_orders`');
		Db::query('TRUNCATE `my_wallet`');
		Db::query('TRUNCATE `my_wallet_log`');
		Db::query('TRUNCATE `orders`');
		Db::query('TRUNCATE `otc_market`');
		Db::query('TRUNCATE `otc_match`');
		Db::query('TRUNCATE `partnerr`');
		Db::query('TRUNCATE `person_service`');
		Db::query('TRUNCATE `proportion`');
		Db::query('TRUNCATE `proportion_copy2`');
		// pro_log real_name real_pass rush_order rush_order_user_list shopcar shop_address shop_cart shop_group shop_order shop_order_goods shop_user_address sign_in_log task user user_apply_log  user_invite_code user_package  withdraw_log
		Db::query('TRUNCATE `pro_log`');
		Db::query('TRUNCATE `real_name`');
		Db::query('TRUNCATE `real_pass`');
		Db::query('TRUNCATE `rush_order`');
		Db::query('TRUNCATE `rush_order_user_list`');
		Db::query('TRUNCATE `shopcar`');
		Db::query('TRUNCATE `shop_address`');
		Db::query('TRUNCATE `shop_cart`');
		Db::query('TRUNCATE `shop_group`');
		Db::query('TRUNCATE `shop_order`');
		Db::query('TRUNCATE `shop_user_address`');
		Db::query('TRUNCATE `sign_in_log`');
		Db::query('TRUNCATE `task`');
		Db::query('TRUNCATE `user`');
		Db::query('TRUNCATE `user_apply_log`');
		Db::query('TRUNCATE `user_invite_code`');
		Db::query('TRUNCATE `user_package`');
		Db::query('TRUNCATE `withdraw_log`');


    }

    /**
     * @power 会员管理|会员列表
     * @rank 1
     */
    public function index(Request $request)
    {
        $totalUser = userModel::where('level', '>', 0)->count();
        $totalno = userModel::where('level', '>', 0)->where('update_time', '<', time() - 3600 * 24)->count();
        $entity = userModel::field('u.*,c.invite_code')->alias('u');

        if ($see = $request->param('see')) {

            $uid = $request->param('id');
            if ($see == '1') {
                $entity->where('u.pid', $uid);
            }
            $map['see'] = 1;
            $map['id'] = $uid;

        }
        if ($level = $request->param('level')) {
            $entity->where('u.level', $level);
            $map['level'] = $level;
        }

        $page = $request->param('page');
        if ($keyword = $request->param('keyword')) {
            $type = $request->param('type');
            switch ($type) {
                case 'nick_name':
                    $entity->where('u.nick_name', $keyword);
                    break;
                case 'mobile':
                    $entity->where('u.mobile', $keyword);
                    break;
                case 'realname':
                    $entity->where('u.real_name', $keyword);
                    break;
                case 'userid':
                    $entity->where('u.id', $keyword);
                    break;
                case 'freeze':
                    $entity->where('w.freeze', '>=', $keyword);
                    break;
                case 'degree_num':
                    $entity->where('w.degree_num', '>=', $keyword);
                    break;
                case 'can_sell':
                    $entity->where('w.can_sell', '>=', $keyword);
                    break;
                case 'sell_number':
                    $entity->where('w.sell_number', '>=', $keyword);
                    break;
            }
            $map['type'] = $type;
            $map['keyword'] = $keyword;
        }


        if ($level = $request->param('level')) {
            $entity->where($level,'>',0);
        }
        if ($status =  $request->param('status')) {
            $entity->where('u.status', $status);
            $map['status'] = $status;
        }
        if ($certification = $request->param('certification')) {
            if ($certification == 2) {
                $entity->where('u.is_certification', -1);
                $entity->where('u.card_left', '<>', NULL);
                $entity->where('u.card_right', '<>', NULL);
            } else {
                $entity->where('u.is_certification', $certification);
            }
            $map['certification'] = $certification;
        }
        $orderStr = 'u.register_time DESC';
        if ($order = $request->param('order')) {
            $sort = $request->param('sort', 'desc');
            $orderStr = 'u.' . $order . ' ' . $sort;
            $map['order'] = $order;
            $map['sort'] = $sort;
        }
        $codeTable = (new UserInviteCode())->getTable();
        $list = $entity->leftJoin("$codeTable c", 'u.id = c.user_id')
            ->field('c.invite_code,u.*,u.id as user_id ,w.money,w.focas,w.coupon,w.bless')
            ->leftJoin("my_wallet w", 'u.id = w.user_id')
            ->order($orderStr)
            ->paginate(15, false, [
                'query' => isset($map) ? $map : [],
                'page' => $page
            ]);
        $user1 = new \app\common\entity\User();
        foreach ($list as $vv) {
            $vv['c'] = MachineList::where('user_id', $vv['id'])->where('status', 1)->where('level', 5)->count();
            $vv['d'] = MachineList::where('user_id', $vv['id'])->where('status', 1)->where('level', 4)->count();
            $vv['z'] = MachineList::where('user_id', $vv['id'])->where('status', 1)->where('level', 3)->count();
            $vv['x'] = MachineList::where('user_id', $vv['id'])->where('status', 1)->where('level', 2)->count();
            $vv['v'] = MachineList::where('user_id', $vv['id'])->where('status', 1)->where('level', 1)->count();
            $childs1 = \app\common\entity\User::where('pid', $vv['user_id'])->field('id')->select();
            $vv['team_num'] = $user1->getChildsNum($childs1);
            $vv['zhitui'] = $user1->where('pid', $vv['id'])->count('id');

            //UserLevelModel::userLelveIndex($vv);

        }
        if (isset($map['sort'])) {
            $map['sort'] = $map['sort'] == 'desc' ? 'asc' : 'desc';
        }

        // dump($list);die;
        return $this->render('index', [
            'list' => $list,
            'user' => new userModel(),
            'queryStr' => isset($map) ? http_build_query($map) : '',
            'totalUser' => $totalUser,
            'totalno' => $totalno,
            'levelModel'=> new UserApplyLogModel(),
        ]);
    }

    public function userListExcelExport(){

    }



    #屏蔽交易订单
    public function unset_buy($id)
    {
        $user = \app\common\entity\User::where('id', $id)->update(['is_buy' => 2]);
        return json(['code' => 0, 'message' => '操作成功']);

    }

    #取消屏蔽交易订单
    public function can_buy($id)
    {
        $user = \app\common\entity\User::where('id', $id)->update(['is_buy' => 1]);
        return json(['code' => 0, 'message' => '操作成功']);

    }

    /**
     * 导出数据
     */
    public function exportUser(Request $request)
    {
        $export = new Export();
        $entity = userModel::field('u.*,c.invite_code')->alias('u');
        if ($level = $request->get('level')) {
            $entity->where('u.level', $level);
            $map['level'] = $level;
        }
        if ($keyword = $request->get('keyword')) {
            $type = $request->get('type');
            switch ($type) {
                case 'mobile':
                    $entity->where('u.mobile', $keyword);
                    break;
                case 'nick_name':
                    $entity->where('u.nick_name', $keyword);
                    break;
            }
            $map['type'] = $type;
            $map['keyword'] = $keyword;
        }
        if ($certification = $request->get('certification')) {
            if ($certification == 2) {
                $entity->where('u.is_certification', -1);
                $entity->where('u.card_left', '<>', NULL);
                $entity->where('u.card_right', '<>', NULL);
            } else {
                $entity->where('u.is_certification', $certification);
            }
            $map['certification'] = $certification;
        }
        $orderStr = 'u.register_time DESC';
        if ($order = $request->get('order')) {
            $sort = $request->get('sort', 'desc');
            $orderStr = 'u.' . $order . ' ' . $sort;
            $map['order'] = $order;
            $map['sort'] = $sort;
        }
        $codeTable = (new UserInviteCode())->getTable();
        $list = $entity->leftJoin("$codeTable c", 'u.id = c.user_id')
            ->field('c.*,u.*,w.ky_number,w.freeze,w.number as ys_number,b.number as blocknumber')
            ->leftJoin("block_wallet b", 'u.id = b.user_id')
            ->leftJoin("my_wallet w", 'u.id = w.user_id')
            ->order($orderStr)
            ->select();
        foreach ($list as $key => &$value) {
            $p = $value->getParentInfo();
            if ($p) {
                $value['p_nick_name'] = $p['nick_name'];
                $value['p_mobile'] = $p['mobile'];
            } else {
                $value['p_nick_name'] = '无';
                $value['p_mobile'] = '无';
            }
            $team = $value->getTeamInfo();
            $value['total'] = $team['total'];
            $value['rate'] = $team['rate'];
            if ($value['is_certification'] == 1) {
                $value['certification'] = '已认证';
            } else {
                $value['certification'] = '未认证';
            }
            if ($value->level == '1') {
                $value['level1'] = 'A级';
            } elseif ($value->level == '2') {
                $value['level1'] = 'B级';
            } elseif ($value->level == '3') {
                $value['level1'] = 'C级';
            } elseif ($value->level == '4') {
                $value['level1'] = 'D级';
            } elseif ($value->level == '5') {
                $value['level1'] = 'E级';
            } elseif ($value->level == '-1') {
                $value['level1'] = '节点';
            } elseif ($value->level == '0') {
                $value['level1'] = '体验';
            }
        }
        // dump($list);die;

        $filename = '会员列表';
        $header = array('会员账号', '会员等级', '邀请码', '上级账号', '福多多资产', '原始资产', '可用资产', '孵化资产', '注册时间', '注册ip', '是否认证');
        $index = array('mobile', 'level1', 'invite_code', 'p_mobile', 'blocknumber', 'ys_number', 'ky_number', 'freeze', 'register_time', 'register_ip', 'certification');
        $export->createtable($list, $filename, $header, $index);
    }

    #一键清除累计充值
    public function deletetotal()
    {
        Db::startTrans();
        $res = Mywallet::where('id', '>', 0)->update(['total_num' => 0]);
        $del = SendMachine::where('tolevel', '>', 5)->update(['is_del' => 2, 'del_time' => time()]);
        if ($res) {
            Db::commit();
            return json(['code' => 0, 'message' => '操作成功']);
        }
        Db::rollback();
        return json(['code' => 1, 'message' => '操作失败']);

    }

    public function changeTrad(Request $request)
    {
        $type = $request->post('type');
        $status = $request->post('status');
        $id = (int)$request->post('id');

        $user = userModel::where('id', $id)->find();
        if (!$user) {
            return json(['code' => 0, 'message' => '会员不存在']);
        }
        if ($type == 'buy') {
            if ($user->is_buy == $status) {
                return json(['code' => 0, 'message' => '会员购买状态没变']);
            }
            $user->is_buy = $status;
            if ($user->save()) {
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 1, 'message' => '操作失败']);
            }
        }
        if ($type == 'sale') {
            if ($user->is_sale == $status) {
                return json(['code' => 0, 'message' => '会员购买状态没变']);
            }
            $user->is_sale = $status;
            if ($user->save()) {
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 1, 'message' => '操作失败']);
            }
        }
        if ($type == 'top') {
            if ($user->is_top == $status) {
                return json(['code' => 0, 'message' => '会员置顶状态没变']);
            }
            $user->is_top = $status;
            if ($user->save()) {
                return json(['code' => 1, 'message' => '操作成功']);
            } else {
                return json(['code' => 1, 'message' => '操作失败']);
            }
        }
    }

    /**
     * 导出茶园明细数据
     * @method get
     */
    public function exportMagic(Request $request)
    {
        $export = new Export();
        $entity = UserProduct::alias('up')->field('up.*,u.mobile, p.product_name, p.yield_max, p.yield_min, p.rate_min, p.rate_max, p.period');
        if ($keyword = $request->get('keyword')) {
            $entity->where('u.mobile', $keyword);
            $map['keyword'] = $keyword;
        }

        if ($type = $request->get('type')) {
            $entity->where('up.types', $type);
            $map['type'] = $type;
        }

        if ($product_id = $request->get('product_id')) {
            $entity->where('up.product_id', $product_id);
            $map['product_id'] = $product_id;
        }

        if ($status = $request->get('status')) {
            if ($status == 2) {
                $entity->where('up.status', 0);
            } elseif ($status == 1) {
                $entity->where('up.status', $status);
            }
            $map['status'] = $status;
        }

        $list = $entity->leftJoin("user u", 'up.user_id = u.id')
            ->leftJoin("product p", 'up.product_id = p.id')
            ->order('up.buy_time', 'desc')
            ->select();
        foreach ($list as $key => &$value) {
            $value['buy_time'] = $value->getBuyTime();
            $value['end_time'] = $value->getEndTime();
            if ($value['status'] == 1) {
                $value['status'] = '运行中';
            } else {
                $value['status'] = '已过期';
            }
            $value['rate'] = $value['rate_max'] . "-" . $value['rate_min'];
            $value['yield'] = $value['yield_max'] . "-" . $value['yield_min'];

            $value['types'] = $value->getType();
        }
        $filename = '茶园明细列表';
        $header = array('产品编号', '会员账号', '茶园类型', '购买时间', '到期时间', '开采率(kb/s)', '日产量(金币)', '昨日收益', '总收益', '以收益天数', '总天数', '状态', '来源');
        $index = array('product_number', 'mobile', 'product_name', 'buy_time', 'end_time', 'rate', 'yield', 'yestoday', 'total', 'balance_day', 'period', 'status', 'types');
        $export->createtable($list, $filename, $header, $index);
    }

    /**
     * 导出充值明细数据
     * @method get
     */
    public function exportRecharge(Request $request)
    {
        $export = new Export();
        $entity = UserMagicLog::alias('um')->field('um.*,u.mobile');
        if ($keyword = $request->get('keyword')) {
            $entity->where('u.mobile', $keyword);
            $map['keyword'] = $keyword;
        }
        if ($type = $request->get('type')) {
            $entity->where('um.types', $type);
            $map['type'] = $type;
        }

        $userTable = (new \app\common\entity\User())->getTable();

        $list = $entity->leftJoin("{$userTable} u", 'um.user_id = u.id')
            ->order('um.create_time', 'desc')
            ->select();
        foreach ($list as $key => &$value) {
            $value['types'] = $value->getType($value['types']);
        }
        $filename = '充值明细列表';
        $header = array('id', '会员账号', '金币数量', '变化前', '变化后', '类型', '备注', '时间');
        $index = array('id', 'mobile', 'magic', 'old', 'new', 'types', 'remark', 'create_time');
        $export->createtable($list, $filename, $header, $index);
    }

    /**
     * @power 会员管理|认证会员列表
     */
    public function certificationlist(Request $request)
    {
        $entity = userModel::field('u.*,c.invite_code')->alias('u');
        if ($level = $request->get('level')) {
            $entity->where('u.level', $level);
            $map['level'] = $level;
        }
        if ($keyword = $request->get('keyword')) {
            $type = $request->get('type');
            switch ($type) {
                case 'mobile':
                    $entity->where('u.mobile', $keyword);
                    break;
                case 'nick_name':
                    $entity->where('u.nick_name', $keyword);
                    break;
            }
            $map['type'] = $type;
            $map['keyword'] = $keyword;
        }
        //
        if ($is_certification = $request->get('is_certification', 1)) {
            $entity->where('u.is_certification', $is_certification);
            $map['is_certification'] = $is_certification;
        }
        $codeTable = (new UserInviteCode())->getTable();
        $list = $entity->leftJoin("$codeTable c", 'u.id = c.user_id')
            ->order('u.register_time', 'desc')
            ->paginate(15, false, [
                'query' => isset($map) ? $map : []
            ]);
        return $this->render('index', [
            'list' => $list,
            'queryStr' => isset($map) ? http_build_query($map) : '',
        ]);
    }

    /**
     * @power 会员管理|充值明细
     * @method GET
     */
    public function magicList(Request $request)
    {
        $entity = BlockLog::alias('um')->field('um.*,u.mobile');
        if ($keyword = $request->get('keyword')) {
            $entity->where('u.mobile', $keyword);
            $map['keyword'] = $keyword;
        }
        if ($types = $request->get('types')) {
            $entity->where('um.types', $types);
            $map['types'] = $types;
        }

        $userTable = (new \app\common\entity\User())->getTable();

        $list = $entity->leftJoin("{$userTable} u", 'um.user_id = u.id')
            ->order('um.create_time', 'desc')
            ->paginate(15, false, [
                'query' => isset($map) ? $map : []
            ]);
        $count = '0';

        return $this->render('magic', [
            'list' => $list,
            'count' => $count,
        ]);
    }

    /**
     * @power 会员管理|茶园明细
     * @method GET
     */
    public function magicboxlist(Request $request)
    {
        $entity = UserProduct::alias('up')->field('up.*,u.mobile, p.product_name, p.yield_max, p.yield_min, p.rate_min, p.rate_max, p.period');
        if ($keyword = $request->get('keyword')) {
            $entity->where('u.mobile', $keyword);
            $map['keyword'] = $keyword;
        }

        if ($type = $request->get('type')) {
            $entity->where('up.types', $type);
            $map['type'] = $type;
        }

        if ($product_id = $request->get('product_id')) {
            $entity->where('up.product_id', $product_id);
            $map['product_id'] = $product_id;
        }

        if ($status = $request->get('status')) {
            if ($status == 2) {
                $entity->where('up.status', 0);
            } elseif ($status == 1) {
                $entity->where('up.status', $status);
            }
            $map['status'] = $status;
        }

        $list = $entity->leftJoin("user u", 'up.user_id = u.id')
            ->leftJoin("product p", 'up.product_id = p.id')
            ->order('up.buy_time', 'desc')
            ->paginate(15, false, [
                'query' => isset($map) ? $map : []
            ]);

        $productList = productModel::select();
        $tmpPro = [];
        foreach ($productList as $v) {
            $tmpPro[$v['id']] = $v['product_name'];
        }
        //统计购买类型
        $resDataList = UserProduct::field('COUNT(*) as count,product_id,types')->group('product_id,types')->select();
        $resDataList = $resDataList->toArray();
        $dataList = [];
        foreach ($resDataList as $k => $v) {
            if (!isset($dataList[$v['product_id']])) {
                $dataList[$v['product_id']]['name'] = $tmpPro[$v['product_id']];
            }
            $dataList[$v['product_id']]['countList'][$v['types']] = $v['count'];
        }
        return $this->render('magicboxlist', [
            'list' => $list,
            'productList' => $productList,
            'dataList' => $dataList,
        ]);
    }

    /**
     * @power 会员管理|茶园明细|撤销茶园
     * @method POST
     */
    public function deleteUserProduct(Request $request)
    {
        $id = $request->post('id');
        $res = UserProduct::destroy($id);
        if ($res) {
            return ['code' => 0, 'message' => '操作成功'];
        } else {
            throw new AdminException('操作失败');
        }
    }

    /**
     * @power 会员管理|会员列表@添加会员
     */
    public function create()
    {
        return $this->render('edit', ['levelcate' => userModel::getAllLevel()]);
    }

    /**
     * @power 会员管理|会员列表@编辑会员
     */
    public function edit($id)
    {
        $entity = userModel::where('id', $id)->find();
        if (!$entity) {
            $this->error('用户对象不存在');
        }

        return $this->render('edit', [
            'info' => $entity,
            'levelcate' => userModel::getAllLevel(),
            'agentlevel' => UserAgentLevelModel::select(),
            'teamlevel' => UserTeamLevelModel::select(),
            'houselevel' => UserHouseLevelModel::select(),
            'arealevel' => UserAreaLevelModel::select(),
        ]);
    }

    /**
     * @power 会员管理|会员列表@充值魔石
     * @method GET
     */
    public function recharge($id)
    {
        $entity = userModel::where('id', $id)->find();
        // var_dump($entity);die;
        if (!$entity) {
            $this->error('用户对象不存在');
        }

        return $this->render('recharge', [
            'types' => MywalletLog::getTypes(),
            'info' => $entity,
        ]);
    }

    /**
     * @power 会员管理|会员列表@充值魔石
     * @method POST
     */
    public function saveRecharge($id, Request $request)
    {
        $remark = $request->post("remark");
        $types = $request->post('types');

        $coin = $request->post('magic');



        if ($coin < 0) {
            $coin1 = abs($coin);
            $inslog = MywalletLog::addLog($id, $coin1, $types, $remark, 1, 2);

        } else {
            $inslog =  MywalletLog::addLog($id, $coin, $types, $remark, 1, 1);

        }
        if (!$inslog) {

            throw new AdminException('充值失败');
        }
        $AdminRegLog = new AdminRegLog();
        $AdminRegLog->addLog($id,$types,$coin,$types);
        return ['code' => 0, 'message' => '充值成功', 'toUrl' => url('index')];
    }

    /**
     * @power 会员管理|会员列表@充值茶园
     * @method GET
     */
    public function rechargemagic($id)
    {
        $entity = userModel::where('id', $id)->find();
        if (!$entity) {
            $this->error('用户对象不存在');
        }

        //得到所有的茶园

        return $this->render('rechargemagic', [
            'info' => $entity,
        ]);
    }

    /**
     * @power 会员管理|会员列表@充值魔石
     * @method POST
     */
    public function saveMagic(Request $request)
    {
        // $magic = $request->post('magic');
        // if (!preg_match('/^[0-9]+?[0-9]*$/', $magic)) {
        //     throw new AdminException('输入的数量必须为正整数');
        // }

        $id = $request->post('id');
        $entity = $this->checkInfo($id);

        $types = $request->post('types');
        $remark = $request->post('remark');
        $num = $request->post('num');
        if ($num < 1) {
            return ['code' => 1, 'message' => '数量不得小于1'];

        }
        $machineModel = new MachineList();
        $res = $machineModel->insMachine($id, $types, '系统充值', $num);
        $machine_type = UserPackage::getOneCate($types);
        (new AdminRegLog())->addLog($id, $num, $machine_type);

        if (!$res) {
            return ['code' => 1, 'message' => '充值失败'];
        }


        return ['code' => 0, 'message' => '充值成功', 'toUrl' => 'index'];
    }

    /**
     * @power 会员管理|会员列表@添加会员
     */
    public function save(Request $request)
    {
        $result = $this->validate($request->post(), 'app\admin\validate\UserForm');

        if (true !== $result) {
            return json()->data(['code' => 1, 'message' => $result]);
        }

        $service = new \app\common\service\Users\Service();
        if ($service->checkMobile($request->post('mobile'))) {
            return json(['code' => 1, 'message' => '账号已被注册,请重新填写']);
            throw new AdminException('账号已被注册,请重新填写');
        }


        $p_nick_name = $request->post('p_nick_name');
        if ($p_nick_name) {

            $p_nick = \app\common\entity\User::where('mobile', $p_nick_name)->find();
            if (!$p_nick) {
                return json(['code' => 1, 'message' => '该上级账号不存在']);

            }
        }
        // Db::startTrans();

        $userId = $service->addUser($request->post());

        if (!$userId) {
            throw new \Exception('保存失败');
        }


        $inviteCode = new UserInviteCode();
        if (!$inviteCode->saveCode($userId)) {
            throw new \Exception('保存失败');
        }
        /*$pid = \app\common\entity\User::where('id',$userId)->value('pid');*/
       /* MywalletLog::register($pid);
        MywalletLog::addLog($userId,Config::getValue('lock_register'), 2, '注册赠送', 9, 1);*/
        // var_dump($my_wallet_id);die;

        if ($inviteCode) {
            // Db::commit();
            return json(['code' => 0, 'toUrl' => url('/admin/user')]);

        }

        // Db::rollback();

        // throw new AdminException($e->getMessage());

    }

    /**
     * @power 会员管理|会员列表@编辑会员
     */
    public function update(Request $request, $id)
    {
        $entity = $this->checkInfo($id);

        $result = $this->validate($request->post(), 'app\admin\validate\UserEditForm');

        if (true !== $result) {
            return json()->data(['code' => 1, 'message' => $result]);
        }
        $area_level = $request->post('area_level');
        if(!empty($area_level)){
            if($area_level == 1){
                $old = \app\common\entity\User::
                where('province',$request->post('province'))
                    ->where('city',$request->post('city'))
                    ->where('area',$request->post('area'))
                    ->where('area_level',$area_level)
                    ->where('id','<>',$id)
                    ->find();
                if($old&& ($request->post('province') || $request->post('city')||$request->post('area') )){
                    return json(['code' => 1, 'message' => '该区域已经存在代理']);
                }
                if(empty($request->post('area'))){
                    return json(['code' => 1, 'message' => '请选择区域']);
                }
            }elseif($area_level == 2){
                if(empty($request->post('city'))){
                    return json(['code' => 1, 'message' => '请选择市']);
                }
                $old = \app\common\entity\User::
                where('province',$request->post('province'))
                    ->where('city',$request->post('city'))
                    ->where('area_level',$area_level)
                    ->where('id','<>',$id)
                    ->find();
                if($old&& ($request->post('province') || $request->post('city')||$request->post('area') )){
                    return json(['code' => 1, 'message' => '该市已经存在代理']);
                }
            }elseif($area_level == 3){
                $old = \app\common\entity\User::
                where('province',$request->post('province'))
                    ->where('area_level',$area_level)
                    ->where('id','<>',$id)
                    ->find();
                if($old&& ($request->post('province') || $request->post('city')||$request->post('area') )){
                    return json(['code' => 1, 'message' => '该省已经存在代理']);
                }
            }
        }

        $service = new \app\common\service\Users\Service();
        $result = $service->updateUser($entity, $request->post());

        if (!$result) {
            throw new AdminException('保存失败');
        }

        return json(['code' => 0, 'toUrl' => url('/admin/user')]);
    }

    /**
     * @power 会员管理|会员列表@禁用会员
     */
    public function delete($id)
    {
        $entity = $this->checkInfo($id);

        $entity->forbidden_time = time();
        $entity->status = \app\common\entity\User::STATUS_FORBIDDED;

        if (!$entity->save()) {
            throw new AdminException('禁用失败');
        }

        return json(['code' => 0, 'message' => 'success']);
    }

    #删除会员
    public function del_user($id, $mobile)
    {
        $userInfo = \app\common\entity\User::where('id', $id)->find();
        if ($userInfo['mobile'] != $mobile) {
            return json(['code' => 1, 'message' => '信息错误']);
        }
        $child = \app\common\entity\User::where('pid', $userInfo['id'])->find();
        if ($child) {
            return json(['code' => 1, 'message' => '该会员有下级不可删除']);
        }
        $market_buy = Market::where('user_id|from_user_id', $userInfo['id'])->where('status', 2)->whereOr('status', 3)->find();

        if ($market_buy) {
            return json(['code' => 1, 'message' => '该会员尚有交易进行中,不可删除']);
        }
        Db::startTrans();
        try {
            \app\common\entity\User::where('id', $userInfo['id'])->delete();
            Mywallet::where('user_id', $userInfo['id'])->delete();
            MywalletLog::where('user_id', $userInfo['id'])->delete();
            UserInviteCode::where('user_id', $userInfo['id'])->delete();
            MachineList::where('user_id', $userInfo['id'])->delete();
            Market::where('user_id', $userInfo['id'])->where('status', 1)->delete();

            Db::commit();
            return json(['code' => 0, 'message' => '删除成功']);

        } catch (Exception $e) {
            Db::rollback();
            return json(['code' => 1, 'message' => '删除失败']);

        }


    }


    /**
     * @power 会员管理|会员列表@解禁会员
     * @method POST
     */
    public function unforbidden($id)
    {
        $entity = $this->checkInfo($id);

        $entity->forbidden_time = 0;
        $entity->status = \app\common\entity\User::STATUS_DEFAULT;

        if (!$entity->save()) {
            throw new AdminException('解禁失败');
        }
        return json(['code' => 0, 'message' => 'success']);
    }

    public function close_no($id)
    {
        $entity = $this->checkInfo($id);

        $entity->close_time = time();
        $entity->is_close = -1;

        if (!$entity->save()) {
            throw new AdminException('禁用失败');
        }

        return json(['code' => 0, 'message' => '禁用成功']);
    }

    public function close_yes($id)
    {
        $entity = $this->checkInfo($id);

        $entity->close_time = time();
        $entity->is_close = 1;

        if (!$entity->save()) {
            throw new AdminException('解封失败');
        }

        return json(['code' => 0, 'message' => '解封成功']);
    }


    /**
     * @power 会员管理|会员列表@手动升级
     * @method POST
     */
    public function level(Request $request)
    {
        if ($request->isPost()) {
            $userId = intval($request->post('user_id'));
            $level = intval($request->post('level'));
            $isReward = intval($request->post('is_reward'));

            $user = \app\common\entity\User::where('id', $userId)->find();
            if (!$user) {
                throw new AdminException('会员不存在');
            }
            if ($user->level == $level) {
                throw new AdminException('会员已是lv' . $level);
            }
            //直接升级
            $user->level = $level;
            if (!$user->save()) {
                throw new AdminException('升级失败');
            }
            //升级处理
            if ($isReward) {
                //赠送奖励
                $model = new \app\common\service\Level\Service();
                $reward = $model->getReward($level);
                $model->sendUserProduct($reward['product_id'], $reward['number'], $user->id);
            }
            return json(['code' => 0, 'message' => '升级成功']);
        }
    }

    private function checkInfo($id)
    {
        $entity = userModel::where('id', $id)->find();
        if (!$entity) {
            throw new AdminException('对象不存在');
        }

        return $entity;
    }


    #套餐配置
    public function package()
    {
        $result = UserLevelSend::where('level','>',0)->order('level asc')->select();
        return $this->render('package', [
            'list' => $result,
            'user' => (new \app\common\entity\User())
        ]);
    }

    #添加配置
    public function packageSetadd(Request $request)
    {
        $data['level'] = $request->post('level');
        $data['num'] = $request->post('num');
        $data['money'] = $request->post('money');
        $data['total_num'] = $request->post('total_num');
        $result = UserPackage::insert($data);
        if (!$result) {
            return ['code' => 1, 'message' => '添加失败'];
        }
        return ['code' => 0, 'message' => '添加成功'];
    }

    #更改配置
    public function packageSetsave(Request $request)
    {
        $id = $request->post('id');
        $result = UserLevelSend::where('id', $id)->find();
        if (!$result) {
            throw new AdminException('操作错误');
        }

        $log = array(

            'pay_money' => $request->post('pay_money'),
            'team_ratio' => $request->post('team_ratio'),
            'direct' => $request->post('direct'),
            'indirect' => $request->post('indirect'),
            'trade' => $request->post('trade'),
            'platform' => $request->post('platform'),
            'level1' => $request->post('level1'),
            'level2' => $request->post('level2'),
            'level3' => $request->post('level3'),
        );
        $res = UserLevelSend::where('id', $id)->update($log);
        if (!$res) {
            return ['code' => 1, 'message' => '修改失败'];
        }
        return ['code' => 0, 'message' => '修改成功'];
    }


    #申述申请
    public function withdrawmoney(Request $request)
    {
        $entity = Db::name('otc_appeal')
            ->alias('um')
            ->field('um.*,u.mobile,u.nick_name,u.level,
            ml.num as market_num,
            buyu.mobile as buy_mobile,buyu.nick_name as buy_nick_name,
            sellu.mobile as sell_mobile,sellu.nick_name as sell_nick_name,
            ml.trade_type');
        if ($keyword = $request->get('keyword')) {
            $entity->where('u.mobile', $keyword);
            $map['keyword'] = $keyword;
        }
        if ($types = $request->get('types')) {
            $entity->where('um.trade_type', $types);
            $map['types'] = $types;
        }

        $userTable = (new \app\common\entity\User())->getTable();

        $list = $entity->leftJoin("{$userTable} u", 'um.user_id = u.id')
            ->leftJoin('otc_match ml', 'um.match_id = ml.id')
            ->leftJoin('user buyu', 'ml.uid = buyu.id')
            ->leftJoin('user sellu', 'ml.from_id = sellu.id')
            ->order('um.create_time', 'desc')
            ->paginate(15, false, [
                'query' => isset($map) ? $map : []
            ]);
        foreach ($list as $key => $v) {
            $v['imgarr'] = explode(",", $v['img']);
        }
        return $this->render('withdrawmoney', [
            'lists' => $list,
        ]);
    }

    #申述拒绝
    public function withdrawmoney_no(Request $request)
    {
        $id = $request->get('id');
        $match_id = $request->get('match_id');
        $matchInfo = OtcMatch::where('id', $match_id)->find();

        $update = ['end_time'=>time()];

        Db::startTrans();
        try {
            $updAppeal = Db::name('otc_appeal')->where('id', $id)->update(['status' => 3]);

            #订单继续，钱买家
            if($matchInfo['success_time'] != 0) {
               OtcMatch::complete($id);
            }
            $update = OtcMatch::where('id', $match_id)->update(['status' => 3, 'end_time' => time()]);
            $market = OtcMarket::where('id', $matchInfo['market_id'])->find();
            if ($market['num'] <= 0) {
                OtcMarket::where('id', $matchInfo['market_id'])->update(['status' => 2, 'end_time' => time()]);
            }
            Db::commit();
            return json()->data(['code' => 0, 'message' => '操作成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json()->data(['code' => 1, 'message' => '操作失败']);
        }


    }

    #申述通过
    public function withdrawmoney_yes(Request $request)
    {
        $id = $request->get('id');
        $match_id = $request->get('match_id');
        $matchInfo = OtcMatch::where('id', $match_id)->find();

        $update = ['end_time'=>time()];
        Db::startTrans();
        try {

            $updAppeal = Db::name('otc_appeal')->where('id', $id)->update(['status' => 2]);

            if($matchInfo['success_time'] != 0){
                if($matchInfo['trade_type'] == 2){
                    //买家封号
                    \app\common\entity\User::where('id',$matchInfo['from_id'])->update(['forbidden_time'=>time(),'status'=>-1]);
                    #订单失效，返还钱给所有卖家
                    $matchList = OtcMatch::where('marker_id',$matchInfo['market_id'])->where('status','in','1,2,4')->where('success_time','>',0)->select();
                    foreach($matchList as $k=>$v){
                        MywalletLog::addLog($v['uid'],$v['pay_gyg'],1,'交易失败全额返币',9,1);
                    }
                    $update = Market::where('marker_id',$matchInfo['market_id'])->where('status','in','1,2,4')->where('success_time','>',0)->update(['status'=>4,'end_time'=>time()]);
                }/*else{
                    //卖家封号
                    \app\common\entity\User::where('id',$matchInfo['uid'])->update(['forbidden_time'=>time(),'status'=>-1]);
                    $update = Market::where('id',$match_id)->update(['status'=>4,'end_time'=>time()]);
                    #@todo 改变订单状态  并返币
                }*/
            }








            Db::commit();
            return json()->data(['code' => 0, 'message' => '操作成功']);
        } catch (\Exception $e) {

            Db::rollback();
            return json()->data(['code' => 1, 'message' => '操作失败']);
        }



       /* Db::startTrans();
        try {*/
           /* $updMessage = Message::where('message_id', $message_id)->update(['status' => 2]);
            $upd = \app\common\entity\Market::where('id', $market_id)->update(['status' => 5]);
            $seal_user = userModel::where('id', $marketInfo['user_id'])->update(['status' => -1]);

            if ($marketInfo['types'] == 1) {

                $mywalletLogModel->addLog($marketInfo['from_user_id'], $marketInfo['num'], '1', '申述成功退回', 1, 1);
                if ($fan_num > 0) {

                    $mywalletLogModel->addLog($marketInfo['from_user_id'], $fan_num, '1', '申述成功退回(手续费)', 3, 1);
                    \app\common\entity\Mywallet::where('user_id', $marketInfo['from_user_id'])->setInc('qytc', $fan_num);
                }

            } elseif ($marketInfo['types'] == 2) {
//                $fan_num = $fan_num + $marketInfo['num'];
                $fan_num = $marketInfo['num'];
                $mywalletLogModel->addLog($marketInfo['from_user_id'], $fan_num, '1', '申述成功退回', 3, 1);

            }*/


           /* Db::commit();
            return json()->data(['code' => 0, 'message' => '操作成功']);
        } catch (\Exception $e) {

            Db::rollback();
            return json()->data(['code' => 1, 'message' => '操作失败']);
        }*/


    }

    #解封列表
    public function unsealingList(Request $request)
    {
        $entity = UnsealingList::alias('um')->field('um.*,u.mobile,u.level');
        if ($keyword = $request->get('keyword')) {
            $entity->where('u.mobile', $keyword);
            $map['keyword'] = $keyword;
        }
        if ($types = $request->get('types')) {
            $entity->where('um.types', $types);
            $map['types'] = $types;
        }

        $userTable = (new \app\common\entity\User())->getTable();

        $list = $entity->leftJoin("{$userTable} u", 'um.user_id = u.id')
            ->order('um.create_time', 'desc')
            ->paginate(15, false, [
                'query' => isset($map) ? $map : []
            ]);

        return $this->render('unsealingList', [
            'lists' => $list,
        ]);
    }

    #解封通过
    public function unsealing_yes(Request $request)
    {
        $id = $request->get('id');
        $upd = UnsealingList::where('id', $id)->update(['status' => 2]);
        $user_id = UnsealingList::where('id', $id)->value('user_id');

        $upd_user_status = \app\common\entity\User::where('id', $user_id)->update(['status' => 1]);
        if ($upd_user_status) {

            return json()->data(['code' => 0, 'message' => '操作成功']);
        }
        return json()->data(['code' => 1, 'message' => '操作失败']);

    }

    #解封拒绝
    public function unsealing_no(Request $request)
    {
        $id = $request->get('id');
        $upd = UnsealingList::where('id', $id)->update(['status' => 3]);
        if ($upd) {

            return json()->data(['code' => 0, 'message' => '操作成功']);
        }
        return json()->data(['code' => 1, 'message' => '操作失败']);

    }


    #支付凭证
    public function voucherList(Request $request)
    {
        $entity = VoucherList::alias('um')->field('um.*,u.mobile,u.level');
        if ($keyword = $request->get('keyword')) {
            $entity->where('u.mobile', $keyword);
            $map['keyword'] = $keyword;
        }
        if ($types = $request->get('types')) {
            $entity->where('um.types', $types);
            $map['types'] = $types;
        }

        $userTable = (new \app\common\entity\User())->getTable();

        $list = $entity->leftJoin("{$userTable} u", 'um.user_id = u.id')
            ->order('um.create_time', 'desc')
            ->paginate(15, false, [
                'query' => isset($map) ? $map : []
            ]);

        return $this->render('voucherList', [
            'lists' => $list,
        ]);
    }

    #支付凭证通过
    public function voucherList_yes(Request $request)
    {
        $voucher_id = $request->get('id');
        $upd1 = VoucherList::where('voucher_id', $voucher_id)->update(['status' => 2]);
        $voucherInfo = VoucherList::where('voucher_id', $voucher_id)->find();
        $insLog = (new MywalletLog())->addLog($voucherInfo['user_id'], $voucherInfo['num'], 'voucher_num', '认筹', 5, 1);
        $upd = \app\common\entity\Mywallet::where('user_id', $voucherInfo['user_id'])->setInc('voucher_num', $voucherInfo['num']);

        if ($upd) {

            return json()->data(['code' => 0, 'message' => '操作成功']);
        }
        return json()->data(['code' => 1, 'message' => '操作失败']);

    }

    #支付凭证拒绝
    public function voucherList_no(Request $request)
    {
        $voucher_id = $request->get('id');
        $upd = VoucherList::where('voucher_id', $voucher_id)->update(['status' => 3]);
        if ($upd) {

            return json()->data(['code' => 0, 'message' => '操作成功']);
        }
        return json()->data(['code' => 1, 'message' => '操作失败']);


    }


    #查看下级
    public function firstToNext(Request $request)
    {
        $user_id = $request->get('id');
        $userModel = new \app\common\entity\User();
        $childs = $userModel->getChildsInfoId($user_id);
        $result = array_reduce($childs, function ($result, $value) {
            return array_merge($result, array_values($value));
        }, array());
        $entity = VoucherList::alias('um')->whereIn('u.id', $result)->where('um.status', 2)->group('um.user_id')
            ->field('um.user_id,sum(um.num) as total_num,u.mobile,u.level');
        if ($keyword = $request->get('keyword')) {
            $entity->where('u.mobile', $keyword);
            $map['keyword'] = $keyword;
        }
        if ($types = $request->get('types')) {
            $entity->where('um.types', $types);
            $map['types'] = $types;
        }
        $userTable = (new \app\common\entity\User())->getTable();

        $list = $entity->leftJoin("{$userTable} u", 'um.user_id = u.id')
            ->order('um.create_time', 'desc')
            ->paginate(15, false, [
                'query' => isset($map) ? $map : []
            ]);
        $count = 0;
        foreach ($list as $a) {
            $count = $a['total_num'] + $count;
        }

        return $this->render('childList', [
            'lists' => $list,
            'count' => $count,
        ]);

    }

    #审核拒绝
    public function mobile_no(Request $request)
    {
        $id = $request->get('id');
        $upd = MobileRecharge::where('id', $id)->update(['status' => 3, 'update_time' => time()]);


        if ($upd) {

            return json()->data(['code' => 0, 'message' => '操作成功']);
        }
        return json()->data(['code' => 1, 'message' => '操作失败']);

    }

    #审核同意
    public function mobile_yes(Request $request)
    {
        $id = $request->get('id');
        $upd = MobileRecharge::where('id', $id)->update(['status' => 2, 'update_time' => time()]);


        if ($upd) {

            return json()->data(['code' => 0, 'message' => '操作成功']);
        }
        return json()->data(['code' => 1, 'message' => '操作失败']);

    }


    #审核列表
    public function realPassList(Request $request)
    {
        $e = RealNameModel::alias('r')->field('r.*,u.nick_name,u.level');
        $list = $e->leftJoin("user u", 'r.uid = u.id')
            ->order('r.createtime desc')
            ->paginate(15, false, [
                'query' => isset($map) ? $map : []
            ]);
        return $this->render('realpassList', [
            'lists' => $list,
        ]);

        /*$entity = RealPass::alias('um')->field('um.*,u.nick_name,u.level');
        if ($keyword = $request->get('keyword')) {
            $type = $request->get('type');
            switch ($type) {
                case 'nick_name':
                    $entity->where('u.nick_name', $keyword);
                    break;
                case 'realname':
                    $entity->where('u.real_name', $keyword);
                    break;
            }
            $map['type'] = $type;

            $map['keyword'] = $keyword;
        }
        if ($types = $request->get('types')) {
            $entity->where('um.types', $types);
            $map['types'] = $types;
        }

        $userTable = (new \app\common\entity\User())->getTable();

        $list = $entity->leftJoin("{$userTable} u", 'um.user_id = u.id')
            ->order('um.create_time', 'desc')
            ->paginate(15, false, [
                'query' => isset($map) ? $map : []
            ]);
        foreach ($list as $vv) {
            $vv['card_img'] = str_replace("../", "/", $vv['card_img']);
        }

        return $this->render('realpassList', [
            'lists' => $list,
        ]);*/
    }
    /**
     * [审核]
     * @param
     * @return
     */
    public function realnamecheck( Request $request ){
        $id = input('id');
        $info = RealNameModel::where('id',$id)->find();
        if(empty($info)) return json()->data(['code'=>1,'message'=>'信息错误,请刷新重试']);
        if($info['status'] !=0) return json()->data(['code'=>1,'message'=>'已审核']);
        $status = input('status');
        RealNameModel::where('id',$id)->update(['status'=>$status,'finishtime'=>time()]);
        return json(['code' => 0, 'toUrl' => url('/admin/user/realPassList')]);
    }
    #审核通过
    public function pass_yes(Request $request)
    {
        $id = $request->get('id');
        $user_id = RealPass::where('id', $id)->value('user_id');
        $user = userModel::where('id', $user_id)->find();
        if ($user['real_pass'] == '2') {
            return json()->data(['code' => 1, 'message' => '该用户已认证']);

        }


        $walletLogModel = new MywalletLog();
        $machineModel = new MachineList();

        $data = [
            'real_pass' => '2',
//            'level' => '1',
        ];

        Db::startTrans();
        try {
            $upd = RealPass::where('id', $id)->update(['status' => 2, 'update_time' => time()]);

            $res = userModel::where('id', $user_id)->update($data);
            userModel::upLevel($user_id);
            Db::commit();
            return json()->data(['code' => 0, 'message' => '操作成功']);

        } catch (\Exception $e) {

            Db::rollback();
            return json()->data(['code' => 1, 'message' => '操作失败']);

        }

    }

    #审核拒绝
    public function pass_no(Request $request)
    {
        $id = $request->get('id');
        $upd = RealPass::where('id', $id)->update(['status' => 3, 'update_time' => time()]);
        $user_id = RealPass::where('id', $id)->value('user_id');
        $res = userModel::where('id', $user_id)->update(['real_pass' => 1]);

        if ($upd) {

            return json()->data(['code' => 0, 'message' => '操作成功']);
        }
        return json()->data(['code' => 1, 'message' => '操作失败']);

    }
    #删除审核
    public function pass_del(Request $request)
    {
        $id = $request->get('id');
        $user_id = RealPass::where('id', $id)->value('user_id');
        $upd = RealPass::where('id', $id)->delete();
        $res = userModel::where('id', $user_id)->update(['real_pass' =>1]);

        if ($upd && $res) {

            return json()->data(['code' => 0, 'message' => '操作成功']);
        }
        return json()->data(['code' => 1, 'message' => '操作失败']);

    }

    #月底结算
    public function month_count()
    {
        $userInfo = userModel::where('level', '>', 0)->limit(2500)->select();
        $user_level_send = Db::table('user_level_send')->select();
        $this_user_num = count($userInfo);

        foreach ($userInfo as $v) {

            if ((time() - strtotime($v['register_time'])) > 3600 * 48) {
                $upd_is_new = userModel::where('id', $v['id'])->update(['is_new' => 1]);
            }
            $total_num = \app\common\entity\Mywallet::where('user_id', $v['id'])->value('total_num');
            if ($v['level'] == '1') {//升2级
                if ($total_num >= $user_level_send[1]['buy_total']) {

                    SendMachine::addList(['uid' => $v['id'], 'tolevel' => 1, 'remark' => '一级买满' . $user_level_send[1]['buy_total'] . '赠送', 'type' => 1]);
                    SendMachine::addList(['uid' => $v['id'], 'tolevel' => 1, 'remark' => '一级买满' . $user_level_send[1]['buy_total'] . '赠送矿池', 'type' => 2]);

                    if ($v['pid'] != '0') {
                        SendMachine::addList(['uid' => $v['pid'], 'tolevel' => 2, 'remark' => $v['mobile'] . '升二级赠送', 'type' => 1]);
                    }

                }

                if ($total_num >= $user_level_send[1]['buy_total']) {

                    SendMachine::addList(['uid' => $v['id'], 'tolevel' => 2, 'remark' => '升二级赠送', 'type' => 1]);
                    SendMachine::addList(['uid' => $v['id'], 'tolevel' => 2, 'remark' => '升二级赠送矿池', 'type' => 2]);
                    userModel::where('id', $v['id'])->update(['level' => 2, 'update_time' => time()]);

                    if ($v['pid'] != '0') {
                        SendMachine::addList(['uid' => $v['pid'], 'tolevel' => 2, 'remark' => $v['mobile'] . '升二级赠送', 'type' => 1]);
                    }

                }

            } elseif ($v['level'] == '2') {//升3级

                if ($total_num >= $user_level_send[2]['buy_total']) {

                    SendMachine::addList(['uid' => $v['id'], 'tolevel' => 3, 'remark' => '升三级赠送', 'type' => 1]);
                    SendMachine::addList(['uid' => $v['id'], 'tolevel' => 3, 'remark' => '升三级赠送矿池', 'type' => 2]);
                    userModel::where('id', $v['id'])->update(['level' => 3, 'update_time' => time()]);

                    if ($v['pid'] != '0') {
                        SendMachine::addList(['uid' => $v['pid'], 'tolevel' => 3, 'remark' => $v['mobile'] . '升二级赠送', 'type' => 1]);

                    }

                }
            } elseif ($v['level'] == '3') {
                if ($total_num >= $user_level_send[3]['buy_total']) {

                    SendMachine::addList(['uid' => $v['id'], 'tolevel' => 4, 'remark' => '升四级赠送', 'type' => 1]);
                    SendMachine::addList(['uid' => $v['id'], 'tolevel' => 4, 'remark' => '升四级赠送矿池', 'type' => 2]);
                    userModel::where('id', $v['id'])->update(['level' => 4, 'update_time' => time()]);
                }


            } elseif ($v['level'] == '4') {
                if ($total_num >= $user_level_send[4]['buy_total']) {

                    SendMachine::addList(['uid' => $v['id'], 'tolevel' => 5, 'remark' => '升五级赠送', 'type' => 1]);
                    SendMachine::addList(['uid' => $v['id'], 'tolevel' => 5, 'remark' => '升五级赠送矿池', 'type' => 2]);
                    userModel::where('id', $v['id'])->update(['level' => 5, 'update_time' => time()]);
                }


            } elseif ($v['level'] == '5') {
                if ($total_num >= $user_level_send[4]['buy_total']) {

                    SendMachine::addList(['uid' => $v['id'], 'tolevel' => 5, 'remark' => '升五级赠送', 'type' => 1]);
                    SendMachine::addList(['uid' => $v['id'], 'tolevel' => 5, 'remark' => '升五级赠送矿池', 'type' => 2]);
                }
            }
            userModel::where('id', $v['id'])->update(['update_time' => time()]);
            Mywallet::where('user_id', $v['id'])->update(['total_num' => 0]);
        }
        return json()->data(['code' => 0, 'message' => '已结算' . $this_user_num . '个用户']);

    }





    #合伙人申请列表
    public function partnerrList(Request $request){
        $entity = Db::name('partnerr')->alias('p')->join('user u ','u.id = p.user_id');
       if ($keyword = $request->get('keyword')) {
           $type = $request->get('type');
           switch ($type) {
               case 'mobile':
                   $entity->where('u.mobile','like','%'. $keyword .'%');
                   break;
               case 'city':
                   $entity->where('p.city', 'like','%'. $keyword .'%');
                   break;
               case 'area':
                   $entity->where('p.area', 'like','%'. $keyword .'%');
                   break;
           }
           $map['type'] = $type;
           $map['keyword'] = $keyword;
       }
       if($status = $request->get('status')) {
           $map['status'] = $status;
           $entity->where('p.status',$status);
       }
       $page = $request->get('page');
       $list = $entity->order('p.id desc')
           ->field('p.*,u.mobile')
           ->paginate(15, false, [
           'query' => isset($map) ? $map : [],
           'page' => $page
       ]);;
        return $this->render('partnerrList', [
            'lists' => $list,
            'queryStr' => isset($map) ? http_build_query($map) : '',
        ]);
    }

    #通过代理审核
    public function partnerr_pass_yes(Request $request){
        $id = $request->param('id');
        $partnerr = Db::name('partnerr')->where('id',$id)->find();

        $where = ['province'=>$partnerr['province'],'city'=>$partnerr['city']];

        if($partnerr['type'] == 2){
            $where['area'] = $partnerr['area'];
        }



        $find = Db::name('partnerr')->where($where)->where('status',2)->find();
        if ($find) {
            return json()->data(['code' => 1, 'message' => '该地区已经有代理了']);
        }
        $data = $partnerr['type'] == 1?['partner'=>1]:['partner2'=>1];
        $update = Db::name('user')->where('id',$partnerr['user_id'])->update($data);

        if (!$update) {
            return json()->data(['code' => 1, 'message' => '操作失败']);
        }

        $update = Db::name('partnerr')->where('id',$id)->update(['status'=>2,'update_time'=>time()]);

        if (!$update) {
            return json()->data(['code' => 1, 'message' => '操作失败']);
        }


        return json()->data(['code' => 0, 'message' => '操作成功']);
    }


    #不通过代理审核
    public function partnerr_pass_no(Request $request){
        $id = $request->param('id');

        $update = Db::name('partnerr')->where('id',$id)->update(['status'=>3,'update_time'=>time()]);
        $partnerr = Db::name('partnerr')->where('id',$id)->find();

        if ($update) {
            MywalletLog::addLog($partnerr['user_id'],$partnerr['money'],1,'不通过代理审核',11,1);
            return json()->data(['code' => 0, 'message' => '操作成功']);
        }
        return json()->data(['code' => 1, 'message' => '操作失败']);
    }






    #合伙人列表
    public function partnerr(Request $request){
        $entity = \app\common\entity\User::alias('u')
            ->join('partnerr p','p.user_id = u.id');
        if ($keyword = $request->get('keyword')) {
            $type = $request->get('type');
            switch ($type) {
                case 'mobile':
                    $entity->where('u.mobile','like','%'. $keyword .'%');
                    break;
                case 'city':
                    $entity->where('p.city', 'like','%'. $keyword .'%');
                    break;
                case 'area':
                    $entity->where('p.area', 'like','%'. $keyword .'%');
                    break;
            }
            $map['type'] = $type;
            $map['keyword'] = $keyword;
        }


        $list = $entity->field('u.id,u.mobile,u.partner,u.partner2')
            ->where('partner2|partner',1)
            ->group('u.id')
            ->paginate(15, false, [
                'query' => isset($map) ? $map : []
            ])->each(function($item){
                if($item['partner']){
                    $item['partner_info'] = Db::name('partnerr')->where(['user_id'=>$item['id'],'type'=>1,'status'=>2])->find();

                        $item['partner_num'] = Db::name('user')->where(['province'=>$item['partner_info']['province'],'city'=>$item['partner_info']['city']])->count();

                }
                if($item['partner2']){
                    $item['partner2_info'] = Db::name('partnerr')->where(['user_id'=>$item['id'],'type'=>2,'status'=>2])->find();

                        $item['partner2_num'] = Db::name('user')->where(['province'=>$item['partner2_info']['province'],'city'=>$item['partner2_info']['city'],'area'=>$item['partner2_info']['area']])->count();

                }



                return $item;
            });



        return $this->render('partnerr', [
            'lists' => $list,
            'queryStr' => isset($map) ? http_build_query($map) : '',
        ]);
    }


    public function add_partnerr(){
        return $this->render('add_partnerr', [
            //'lists' => $list,
            'queryStr' => isset($map) ? http_build_query($map) : '',
        ]);
    }

    public function insertPaetnerr(Request $request){

        if(!$request->post('mobile')){
            return json(['code' => 1, 'message' => '请输入用户手机号码']);
        }
        $user = \app\common\entity\User::where('mobile',$request->post('mobile'))->find();
        if(!$user){
            return json(['code' => 1, 'message' => '该用户不存在']);
        }
        if(!$request->post('city') || !$request->post('province')){
            return json(['code' => 1, 'message' => '请选择地区']);
        }
        $Partnerr = new Partnerr();
        if($request->post('type') == 1){
            $data = [
                'user_id'=>$user['id'],
                'type'=>1,
                'province'=>$request->post('province'),
                'city'=>$request->post('city'),
                'create_time'=>time(),
                'status'=>2,
                'money'=>0
            ];
            if($user['partner']){
                return json(['code' => 1, 'message' => '该用户已是市级合伙人']);
            }
            $infoWhere = ['type'=>1,'province'=>$data['province'],'city'=>$data['city'],'status'=>2];

        }else{
            if(!$request->post('area')){
                return json(['code' => 1, 'message' => '请选择区/县']);
            }
            $data = [
                'user_id'=>$user['id'],
                'type'=>2,
                'province'=>$request->post('province'),
                'city'=>$request->post('city'),
                'area'=>$request->post('area'),
                'create_time'=>time(),
                'status'=>2,
                'money'=>0
            ];

            if($user['partner2']){
                return json(['code' => 1, 'message' => '该用户已是区/县级合伙人']);
            }
            $infoWhere = ['type'=>2,'province'=>$data['province'],'city'=>$data['city'],'status'=>2,'area'=>$data['area']];
        }
        $info = $Partnerr->where(['type'=>1,'province'=>$data['province'],'city'=>$data['city'],'status'=>2])->find();
        if($info){
            return json(['code' => 1, 'message' => '该地区已有代理']);
        }
        $infoWhere['user_id'] = $user['id'];
        $info = $Partnerr->where($infoWhere)->find();
        if($info){
            return json(['code' => 1, 'message' => '该用户已是该地区合伙人，请不要重复提交']);
        }

        $insert = $Partnerr->insert($data);
        if($insert){
            if($request->post('type') == 1){
                \app\common\entity\User::where('id',$user['id'])->update(['partner'=>1]);
            }else{
                \app\common\entity\User::where('id',$user['id'])->update(['partner2'=>1]);
            }
            return json(['code' => 0, 'message' => '添加合伙人成功']);
        }else{
            return json(['code' => 1, 'message' => '添加合伙人失败']);
        }
    }
    public function deletePaetnerr(Request $request){
        $uid = $request->param('id');
        if(!$uid){
            return json(['code' => 1, 'message' => '请求id错误']);
        }
        $info = Partnerr::where('user_id',$uid)->where('type',$request->param('type'))->where('status',2)->find();
        
        if(!$info){
            return json(['code' => 1, 'message' => '请求信息错误']);
        }
        $delete = Partnerr::where('id',$info['id'])->delete();
        if($delete){
            if($request->param('type') == 1){
                \app\common\entity\User::where('id',$uid)->update(['partner'=>0]);
            }else{
                \app\common\entity\User::where('id',$uid)->update(['partner2'=>0]);
            }
            return json(['code' => 0, 'message' => '取消合伙人成功']);
        }
        return json(['code' => 1, 'message' => '取消合伙人失败']);
    }


    #地区下的已绑定会员
    public function partenerrDetail(Request $request){
        $uid = $request->get('id');
        if(!$uid){
            return json(['code' => 1, 'message' => '请求id错误']);
        }
        $type = $request->get('type',1);

        $map = ['type'=>$type,'id'=>$uid];

        $page = $request->get('page',1);

        $info = Partnerr::where('user_id',$uid)->find();
        if($type == 1){
            $where = ['province'=>$info['province'],'city'=>$info['city']];
        }else{
            $where = ['province'=>$info['province'],'city'=>$info['city'],'area'=>$info['area']];
        }
        $user_list = \app\common\entity\User::where($where)
            ->field('id,mobile,real_name,level,pos,province,city,area,address,register_time')
            ->paginate(15, false, [
            'query' => isset($map) ? $map : [],
            'page' => $page
        ]);
        return $this->render('partenerr_detail', [
            'list' => $user_list,
            'queryStr' => isset($map) ? http_build_query($map) : '',
            'user'=>new \app\common\entity\User(),
        ]);

    }

    /**身份等级申请
     * @param Request $request
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function applyPassList(Request $request)
    {
        $e = UserApplyLogModel::alias('r')->field('r.*,u.nick_name,u.mobile');
        $list = $e->leftJoin("user u", 'r.uid = u.id')
            ->order('r.createtime desc')
            ->paginate(15, false, [
                'query' => isset($map) ? $map : []
            ]);
        return $this->render('applypassList', [
            'lists' => $list,
            'model'=>new UserApplyLogModel()
        ]);
    }


    public function applynamecheck(Request $request){
        $info = UserApplyLogModel::where('id',$request->param('id'))->find();
        if(!$info){
            return json(['code' => 1, 'message' => '请求信息错误']);
        }
        if($request->param('status') == 1){
            switch ($info['leveltype']){
                case 1:
                    $update = \app\common\entity\User::where('id',$info['uid'])->update(['team_level'=>$info['levelid']]);
                    break;
                case 2:
                    $update = \app\common\entity\User::where('id',$info['uid'])->update(['agent_level'=>$info['levelid'],'agent_over_time'=>time()+2592000]);
                    break;
                case 3:
                    $update = \app\common\entity\User::where('id',$info['uid'])->update(['house_level'=>$info['levelid'],'house_over_time'=>time()+2592000]);
                    break;
                case 4:
                    $old = \app\common\entity\User::where('province',$info['province'])
                        ->where('city',$info['city'])
                        ->where('area',$info['area'])
                        ->find();
                    if($old){
                        return json(['code' => 1, 'message' => '该区域已经存在代理']);
                    }
                    $update = \app\common\entity\User::where('id',$info['uid'])->update([
                        'area_level'=>$info['levelid'],
                        'area_over_time'=>time()+2592000,
                        'province'=>$info['province'],
                        'city'=>$info['city'],
                        'area'=>$info['area'],
                    ]);
                    break;
                case 3:
                    $update = \app\common\entity\User::where('id',$info['uid'])->update(['partner_level'=>1,'agent_over_time'=>time()+2592000]);
                    break;
                default:
                    return json(['code' => 1, 'message' => '请求信息错误']);
            }
            if(!$update){
                return json(['code' => 1, 'message' => '审核失败']);
            }
        }

        $edit = UserApplyLogModel::where('id',$request->param('id'))->update(['status'=>$request->param('status'),'finishtime'=>time()]);

        return json(['code' => 0, 'message' => '审核成功']);
    }
}
